// pages/operation-center/add-customer/index.js
const app = getApp()
Page({
  data: {
    expand: false,
    showLevelSelector: false,
    starList: [
      { id: 1, value: 1, star: [1, 0, 0, 0, 0] },
      { id: 2, value: 2, star: [1, 1, 0, 0, 0] },
      { id: 3, value: 3, star: [1, 1, 1, 0, 0] },
      { id: 4, value: 4, star: [1, 1, 1, 1, 0] },
      { id: 5, value: 5, star: [1, 1, 1, 1, 1] },
    ],
    currentType: 0,
    currentTypeName: '',
    title: '添加客户',
    op: 'ajaxCustomerAdd',
    customerInfo: {
      business: [], // 初始化business字段
      isopen: '0'
    },
    windowType: 'phone',
    windowPhone: '',
    windowName: '',
    windowJobPosition: '',
    windowInvoiceName: '',
    windowInvoiceSbh: '',
    windowInvoiceAddr: '',
    windowInvoicePhone: '',
    windowInvoiceKhh: '',
    windowInvoiceKhzh: '',
    isOpen: 0,
    userList: [],
    selectedUserCount: 0,
  },

  onLoad(option) {
    this.getUserList(option.id)
  },

  getCustomerInfo(id) {
    app.axios('customer', {
      op: 'ajaxCustomerDetail',
      id: id
    }).then(res => {
      if (res.code) {
        // 处理phoneinfo
        if (res.item.phoneinfo) {
          try {
            if (typeof res.item.phoneinfo === 'string') {
              res.item.phoneinfo = JSON.parse(res.item.phoneinfo)
            }
            if (Object.keys(res.item.phoneinfo).length === 0) {
              res.item.phoneinfo = null
            }
          } catch (e) {
            console.error('phoneinfo解析失败:', e)
            res.item.phoneinfo = null
          }
        }

        // 处理business字段
        if (res.item.business) {
          try {
            res.item.business = JSON.parse(res.item.business)
          } catch (e) {
            console.error('business解析失败:', e)
            res.item.business = []
          }
        } else {
          res.item.business = []
        }

        // 处理phoneList
        if (res.item.phoneinfo && Object.keys(res.item.phoneinfo).length > 0) {
          res.item.phoneList = this.formatPhoneList(res.item.phoneinfo)
        }

        // 处理用户可见范围
        if (res.item.userrange) {
          const selectedIds = res.item.userrange.split(',')
          this.setData({
            userList: this.data.userList.map(user => ({
              ...user,
              selected: selectedIds.includes(String(user.id))
            })),
            selectedUserCount: selectedIds.length
          })
        }

        this.setData({
          customerInfo: res.item
        })
      }
    })
  },

  formatPhoneList(phoneinfo) {
    return Object.keys(phoneinfo).map(phone => ({
      phone: phone,
      xm: phoneinfo[phone].xm,
      zw: phoneinfo[phone].zw
    }))
  },

  navigateTo(e) {
    app.navigateTo(e.currentTarget.dataset.url, e.currentTarget.dataset.type)
  },

  toggleExpand() {
    this.setData({ expand: !this.data.expand })
  },

  toggleLevelSelector() {
    this.setData({ showLevelSelector: !this.data.showLevelSelector })
  },

  changeLevel(e) {
    const id = e.currentTarget.dataset.id
    const selectedStar = this.data.starList.find(item => item.id === id)
    if (selectedStar) {
      this.setData({
        'customerInfo.level': selectedStar.value
      })
    }
  },

  deletePhone(e) {
    const item = e.currentTarget.dataset.item
    const phoneToDelete = item.phone
    const customerInfo = this.data.customerInfo

    const newPhoneList = customerInfo.phoneList.filter(
      phoneItem => phoneItem.phone !== phoneToDelete
    )

    const phoneinfo = { ...customerInfo.phoneinfo }
    delete phoneinfo[phoneToDelete]

    this.setData({
      'customerInfo.phoneList': newPhoneList,
      'customerInfo.phoneinfo': phoneinfo
    })
  },

  showPop(e) {
    const alert = this.selectComponent('#v-alert')
    alert.showAlert()
    this.setData({
      windowType: e.currentTarget.dataset.type
    })
  },

  hidePop() {
    const alert = this.selectComponent('#v-alert')
    alert.hideAlert()
  },

  confirm(e) {
    if (this.data.windowType === 'phone') {
      this.handlePhoneConfirm()
    } else if (this.data.windowType === 'invoice') {
      this.handleInvoiceConfirm()
    }
  },

  handlePhoneConfirm() {
    const { windowPhone, windowName, windowJobPosition } = this.data

    if (!windowPhone || !windowName) {
      wx.showToast({ title: '手机号和姓名不能为空', icon: 'none' })
      return
    }

    const isExist = this.data.customerInfo.phoneList?.some(
      item => item.phone === windowPhone
    )

    if (isExist) {
      wx.showToast({ title: '该手机号已存在', icon: 'none' })
      return
    }

    const newPhoneItem = {
      phone: windowPhone,
      xm: windowName,
      zw: windowJobPosition
    }

    this.setData({
      'customerInfo.phoneinfo': {
        ...this.data.customerInfo.phoneinfo,
        [windowPhone]: {
          xm: windowName,
          zw: windowJobPosition
        }
      },
      'customerInfo.phoneList': [
        ...(this.data.customerInfo.phoneList || []),
        newPhoneItem
      ],
      windowPhone: '',
      windowName: '',
      windowJobPosition: ''
    })

    this.hidePop()
  },

  handleInvoiceConfirm() {
    const {
      windowInvoiceName,
      windowInvoiceSbh,
      windowInvoiceAddr,
      windowInvoicePhone,
      windowInvoiceKhh,
      windowInvoiceKhzh
    } = this.data

    if (!windowInvoiceName) {
      wx.showToast({ title: '单位名称不能为空', icon: 'none' })
      return
    }

    const newInvoice = {
      id: Date.now(),
      name: windowInvoiceName,
      sbh: windowInvoiceSbh,
      addr: windowInvoiceAddr,
      phone: windowInvoicePhone,
      khh: windowInvoiceKhh,
      khzh: windowInvoiceKhzh
    }

    this.setData({
      'customerInfo.business': [
        ...(this.data.customerInfo.business || []),
        newInvoice
      ],
      windowInvoiceName: '',
      windowInvoiceSbh: '',
      windowInvoiceAddr: '',
      windowInvoicePhone: '',
      windowInvoiceKhh: '',
      windowInvoiceKhzh: ''
    })

    this.hidePop()
  },

  deleteInvoice(e) {
    const item = e.currentTarget.dataset.item
    const business = this.data.customerInfo.business.filter(
      invoice => invoice.id !== item.id
    )
    this.setData({
      'customerInfo.business': business
    })
  },

  toggleMapMarker() {
    const mapMarker = this.selectComponent('#v-map')
    mapMarker.toggleMapMarker()
  },

  comitMapResult(res) {
    this.setData({
      'customerInfo.address': res.detail.selectedAddress,
      'customerInfo.clat': res.detail.userLocation.latitude,
      'customerInfo.clng': res.detail.userLocation.longitude,
    })
  },

  handleInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`customerInfo.${field}`]: e.detail.value
    })
  },

  toggleIsOpen() {
    if (this.data.customerInfo.isopen == 0) {
      const selector = this.selectComponent('#user-selector')
      selector.toggleDrawer()
    }
    this.setData({
      'customerInfo.isopen': this.data.customerInfo.isopen === '0' ? '1' : '0'
    })
  },

  getUserList(id) {
    app.axios('user', { op: 'ajaxUserDlList' }).then(res => {
      if (res.code && res.lists?.length) {
        const userList = res.lists.map(user => ({
          ...user,
          selected: false
        }))
        this.setData({ userList })
        if (id) {
          this.setData({
            title: '编辑客户',
            op: 'ajaxCustomerUp'
          })
          this.getCustomerInfo(id)
        }
      }
    })
  },

  confirmUserList() {
    const selectedUsers = this.data.userList
      .filter(user => user.selected)
      .map(user => user.id)

    this.setData({
      'customerInfo.userrange': selectedUsers.toString(),
      selectedUserCount: selectedUsers.length
    })

    const selector = this.selectComponent('#user-selector')
    selector.toggleDrawer()

    wx.showToast({
      title: `已选择${selectedUsers.length}人`,
      icon: 'none'
    })
  },

  selectUser(e) {
    const selectedItem = e.currentTarget.dataset.item
    const userList = this.data.userList.map(user =>
      user.id === selectedItem.id
        ? { ...user, selected: !user.selected }
        : user
    )
    this.setData({ userList })
  },

  saveForm() {
    const customerInfo = JSON.parse(JSON.stringify(this.data.customerInfo))

    // // 转换字段为字符串
    // if (customerInfo.phoneinfo) {
    //   customerInfo.phoneinfo = JSON.stringify(customerInfo.phoneinfo)
    // }

    // // 转换business数组为字符串
    // customerInfo.business = JSON.stringify(customerInfo.business || [])

    // 处理phones参数
    const phoneNumbers = (customerInfo.phoneList || []).map(item => item.phone)
    const phones = phoneNumbers.join(',')

    const params = {
      ...customerInfo,
      phones: phones,
      op: this.data.op
    }
    console.log(params)
    console.log(22222222222222)

    app.axios('customer', params).then(res => {
      if (res.code) {
        wx.showToast({ title: '保存成功', icon: 'success' })
        setTimeout(() => {
          app.navigateTo('/pages/operation-center/index/index?activeTab=0', 'redirectTo')
        }, 1500)
      }
    })
  }
})